#!/usr/bin/perl -w
use strict;

if (@ARGV == 0) {
    print STDERR <<"EOF";
usage:
$0 MODULE PF_LIST OUTPUT_TMA
    Make sure OUTPUT_TMA is a full name like: 3HED19102101.tma
EOF
    exit 0
}

my ($module, $pf, $tma) = @ARGV;
my $module_file;
my $MODPATH = "/mnt/d/zerox/work/script/tma/yjin/module";
if (-f $module) {
    $module_file = $module;
} elsif (-f "$MODPATH/$module") {
    $module_file = "$MODPATH/$module";
} else {
    die "$module: cannot find the module file.";
}

#
# load die information from pf file
#

# key words
my %KW;

open (PF, "< $pf") or die $!;
my %ic;
while (<PF>) {
    next unless /^[\d-]/;
    chomp;
    s/\r$//;
    ## correct line
    my ($x, $y, $pf) = split ',';
    if ($pf =~ /^\W*P\W*$/) {
        $pf = 'P';
    } elsif ($pf =~ /^\W*F\W*$/) {
        $pf = 'F' ;
    } else {
        die "Unknown pass/fail: $pf\n";
    }
    print STDERR "collecting: ($x, $y) = $pf\r";
    $ic{$y}->{$x} = $pf;

    # performe some statistic work
    if (uc($pf) eq 'P') {
        $KW{'passdie'}++;
    } elsif (uc($pf) eq 'F') {
        $KW{'faildie'}++;
    } else {
        warn "unsupported status at ($x, $y)";
    }
    $KW{'totaldie'}++;
}
print STDERR "\n";
$KW{'yield'} = sprintf ("%.2f%%", $KW{'passdie'} / $KW{'totaldie'} * 100);

# load lot id wafer id from tma file name
if ($tma =~ /^(\w{9})\.?(\d{1,2})-?(\d{2})/) {
    $KW{'lotid'} = "$1.$2";
    $KW{'waferid'} = "$1.$2-$3";
    print STDERR "Lot ID: $KW{lotid}\nWafer ID: $KW{waferid}\n";
}

unless (exists $KW{'lotid'}) {
    $KW{'lotid'} = '3HEC00000.0';
}

unless (exists $KW{'waferid'}) {
    $KW{'waferid'} = '3HEC00000.0-00';
}

## IMPORTANT
## there is an assumption, that y address decreases from top to bottom
my @yadr_list_dec = sort {$b <=> $a} keys(%ic);
my @line = map { $ic{$_} } @yadr_list_dec;
print STDERR "Total @{[scalar @line]} rows: [@yadr_list_dec]\n";
my $total_count = 0;
for my $y (@yadr_list_dec) {
    my $row_count = scalar(keys %{$ic{$y}});
    $total_count += $row_count;
    printf STDERR "Row [%2d]: %d\n", $y, $row_count;
}
print STDERR "Total as counted: $total_count\n";
close (PF) or die $!;

#
# load module
#
open(MOD, "< $module_file") or die $!;
open(TMA, "> $tma") or die $!;

my $field = 1;

while(<MOD>) {
    # count the rate of occurrence that dollar appears
    my $count = 0;
    $count++ while (/\$[^\d\W]\w*/g);

    $field = 0 if (/wafer\ information/i);

    if ($count > 0) {
        # if '$' appears
        if ($field == 1) {
            # in the map field
            my $yadr = shift @line;
            die("insuffcient data") if ($count != keys(%$yadr));
            my @fd = split(/\$X/);
            for my $x (sort {$b <=> $a} keys(%$yadr)) {
                print TMA shift @fd;
                print TMA $yadr->{$x};
            }
            print TMA shift @fd while (@fd > 0);
        } else {
            # in the meta info. field
            # replace keywords by their values
            s/\$([^\d\W]\w*)/${KW{$1}}/g;
            print TMA $_;
        }
    } else {
        print TMA $_;
    }
}
